import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Link, browserHistory} from 'react-router'
import { getPixiv } from 'actions/'
import { isObjectEqual, isMobile } from 'util'
import GameList from '../Game'
import AnimeList from '../Anime'
import Masonry from 'react-masonry-component'
import LazyLoad from 'react-lazyload'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'
import Loading from 'components/Loading'
import Message from 'components/Message'
import FriendLink from './mod/friendLink'
import './home'

const masonryOptions = {
    transitionDuration: 0
}
class Home extends Component {
    constructor(props) {
    super(props)
        this.state = {
            type: 'weekly',
            dataSource: [],
            page: 1,
            pageNum: 50,
        }
    }

    componentWillMount() {
        document.title = '99496动漫网(9站) - 在线动漫|动画|漫画|动漫追番|动漫社区|百度云盘分享'
        const { _getPixiv } = this.props
        const { type } = this.state
        const _this = this
        _getPixiv.data ? null : this.getData(0, type)
        document.onkeydown=function(e){
            e = e || event;
            var key=e.keyCode || e.charCode;
            if(key==13) _this.getData(0, 'search')
        }
    }

    handleLayoutComplete(){
        const { type } = this.state
        this.getData(0, type)
    }

    handleScroll(e) {
        if (this.isBottom()) {
            const { type } = this.state
            this.setState({
                page: this.state.page + 1
            })
            this.getData(0 ,type, 20)
        }
    }

    componentDidMount() {
        this.masonry.on('layoutComplete', this.handleLayoutComplete());
        window.addEventListener('scroll', this.handleScroll.bind(this));
    }

    componentWillUnmount(){
        this.masonry.off('layoutComplete', this.handleLayoutComplete())
        window.removeEventListener('scroll', this.handleScroll.bind(this));
    }

    isBottom(){
        const viewHeight = document[document.compatMode == 'CSS1Compat'?'documentElement':'body'].clientHeight;
        const scrollHeight = document.body.scrollHeight;
        const scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        if (scrollTop + viewHeight >= scrollHeight){
             console.log("到达底部");
             return true
        }else{
            return false
        }
    }

    getData(isClick, type, pageNum, page){
        const {dispatch} = this.props
        const isType = !(type === 'original' || type === 'male' || type === 'female' || type === 'search')
        this.setState({
            type,
            dataSource: isClick ? [] : this.state.dataSource,
            page: isClick ? 1 : this.state.page,
        },() => {
            const { word } = this.state
            let params = {}
            if(isType){
                params = {
                    type: 'rank',
                    id: 0
                }
            }

            if(type === 'search'){
                if(word){
                    params = {
                        type,
                        word,
                        page: isClick ? 1 : (page ? page : this.state.page),
                    }
                }else{
                    Message.error('请输入你要搜索的关键字')
                    return false
                }
            }else{
                params = Object.assign(params,{
                    content: 'illust',
                    per_page: pageNum ? pageNum : this.state.pageNum,
                    page: page ? page : this.state.page,
                    mode: type
                })
            }
            dispatch(getPixiv(params)).then((data) => {
                if(data.msg === 'success'){
                    if(type === 'search' ? data.data.list.length : data.msg === 'success'){
                        this.setState({
                            dataSource: isType ? this.state.dataSource.concat(data.data.list[0].works) : (type === 'search' ? this.state.dataSource.concat(data.data.list) : this.state.dataSource.concat(data.data.list))
                        })
                    }
                }
            })
        })
    }

    getWords(e){
        const word = e.target.value
        if(!word){
            this.setState({
                type: 'weekly',
                dataSource: [],
                page: 1
            }, () =>{this.getData(0, this.state.type)})
        }
        this.setState({
            word
        })
    }

    pixivList(){
        const { dataSource, type } = this.state
        const isType = !(type === 'original' || type === 'male' || type === 'female' || type === 'search')
        const dataWorks = dataSource || []
        const renderList = dataWorks.length ? dataWorks.map((items,i) =>{
            const item = isType ? items.work : items
            const imgWidth = isMobile() ? item.width*2 : item.width
            return <li key={i} data-height={item.height} data-width={imgWidth} style={{height: (item.height)*403/imgWidth}} >
                        <a target="_blank" href={`https://www.pixiv.net/member_illust.php?mode=medium&illust_id=${item.id}`}>
                            <LazyLoad throttle={200} height={(item.height)*403/imgWidth}>
                                <ReactCSSTransitionGroup
                                    key={i}
                                    transitionName="fade"
                                    transitionAppear={true}
                                    transitionAppearTimeout={500}
                                    transitionEnter={false}
                                    transitionLeave={false}
                                >
                                    <img src={isType ? items.work.image_urls.px_480mw : items.image_urls.px_480mw} style={{height: (item.height)*403/imgWidth}} />
                                </ReactCSSTransitionGroup>
                            </LazyLoad>
                            <p>{item.title}</p>
                            <em>{item.user.name}</em>
                        </a>
                    </li>
        }) : <Loading />
        return renderList
    }

    render() {
        const { type } = this.state
        const isDis = type === 'search' ? 'hide' : 'show'
        return(
            <div className='wp'>
                <AnimeList indexNum={true} />
                <GameList {...this.props} indexNum={true} />
                <div className='search index-search clearfix'><input type='text' placeholder='搜索你喜欢的关键词，什么都可以搜。' onChange={(e) => this.getWords(e)} /><button onClick={() => this.getData(1,'search')}>搜索</button></div>
                <ul className={`j-tab ${isDis}`}>
                    <li onClick={() => this.getData(1,'weekly')} className={type === 'weekly' ? 'cur' : ''}>周榜</li>
                    <li onClick={() => this.getData(1,'daily')} className={type === 'daily' ? 'cur' : ''}>日榜</li>
                    <li onClick={() => this.getData(1,'monthly')} className={type === 'monthly' ? 'cur' : ''}>月榜</li>
                    <li onClick={() => this.getData(1,'rookie')} className={type === 'rookie' ? 'cur' : ''}>新人</li>
                    <li onClick={() => this.getData(1,'original')} className={type === 'original' ? 'cur' : ''}>原创</li>
                    <li onClick={() => this.getData(1,'male')} className={type === 'male' ? 'cur' : ''}>男性向</li>
                    <li onClick={() => this.getData(1,'female')} className={type === 'female' ? 'cur' : ''}>女性向</li>
                </ul>
                <Masonry
                    className={'j-gallery'}
                    ref={function(c) {this.masonry = this.masonry || c.masonry;}.bind(this)}
                >
                    {this.pixivList()}
                </Masonry>
                <FriendLink />
            </div>
        )
    }
}

function mapStateToProps({getPixiv}) {
    return {
        _getPixiv: getPixiv,
    }
}

export default connect(mapStateToProps)(Home)
